// 文件路径：src/main/java/com/lxp/userms/exception/GlobalExceptionHandler.java
package com.lxp.userms.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(org.springframework.dao.DuplicateKeyException.class)
    public ModelAndView handleDuplicateLike(HttpServletRequest request) {
        String referer = request.getHeader("Referer");
        ModelAndView modelAndView = new ModelAndView();

        // 设置错误信息
        modelAndView.addObject("error", "您已经点过赞了！");

        // 如果有来源页面，则跳转回去
        if (referer != null && !referer.isEmpty()) {
            modelAndView.setViewName("redirect:" + referer);
        } else {
            modelAndView.setViewName("redirect:/default-error-page");
        }

        return modelAndView;
    }
}
